package org.xt.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.xt.constants.Res;
import org.xt.entity.DataItem;
import org.xt.entity.DataMachine;
import org.xt.entity.DataStation;
import org.xt.entity.OutputItem;
import org.xt.entity.Permission;
import org.xt.entity.User;

@IocBean(name="OutputService")
public class OutputItemService {
	@Inject
	private Dao dao;
	
	public Res add(OutputItem item){
		item.setCreateTime(new Date());
		item.setUpdateTime(new Date());
		try{
			item = dao.insert(item);
			if(item == null){
				return Res.NEW().code(Res.ERROR).msg("添加失败");
			}else{
				return Res.NEW().code(Res.SUCCESS).msg("添加成功").data(item);
			}
		}catch(Exception e){
			if(e.getMessage().contains("Violation of PRIMARY KEY constraint")){
				return Res.NEW().code(Res.ERROR).msg("数据库已有此数据，切勿重复添加");
			}else{
				return Res.NEW().code(Res.ERROR).msg("系统异常，请重试");
			}
		}
	}
	public Res update(OutputItem item){
		item.setUpdateTime(new Date());
		try{
			int sum = dao.updateIgnoreNull(item);
			if(sum <= 0){
				return Res.NEW().code(Res.ERROR).msg("更新失败");
			}else{
				return Res.NEW().code(Res.SUCCESS).msg("更新成功").data(item);
			}
		}catch(Exception e){
			return Res.NEW().code(Res.ERROR).msg("系统异常，请重试");
		}
	}
	public Res delete(OutputItem item){
		try{
			int sum = dao.deletex(OutputItem.class, item.getMachineId(), item.getStationId(), item.getItemId());
			if(sum <= 0){
				return Res.NEW().code(Res.ERROR).msg("删除失败");
			}else{
				return Res.NEW().code(Res.SUCCESS).msg("删除成功").data(item);
			}
		}catch(Exception e){
			return Res.NEW().code(Res.ERROR).msg("系统异常，请重试");
		}
	}
	/**
	 * 根据机种ID获取数据库数据，然后转换为级联数据列表，包括样式
	 * @param machineId
	 * @return
	 */
	public NutMap list(int machineId){
		NutMap nmMachine = NutMap.NEW();
		DataMachine dm = dao.fetch(DataMachine.class, machineId);
		nmMachine.addv("name", dm.getName());
		List<NutMap> listNmStation = new ArrayList<>();
		List<DataStation> listStation = findStation(machineId);
		for(DataStation station: listStation){
			NutMap nmStation = NutMap.NEW();
			nmStation.addv("name", station.getName());
			List<NutMap> listNmItem = new ArrayList<>();
			List<DataItem> listItem = findItem(machineId, station.getId());
			for(DataItem item: listItem){
				NutMap nmItem = NutMap.NEW();
				nmItem.addv("name", item.getName());
				nmItem.addv("stopCascade", "true");
				OutputItem outputItem = dao.fetchx(OutputItem.class, machineId, station.getId(), item.getId());
				nmItem.addv("target", outputItem);
				List<NutMap> data = new ArrayList<>();
				data.add(NutMap.NEW().addv("descript", "该项目的target").addv("name", outputItem.getTarget()));
				User opUser = dao.fetch(User.class, outputItem.getOpUserId());
				data.add(NutMap.NEW().addv("descript", "数据用户").addv("name", opUser.getUsername()));
				User opTargetUser = dao.fetch(User.class, outputItem.getOpTargetUserId());
				data.add(NutMap.NEW().addv("descript", "更改target用户").addv("name", opTargetUser.getUsername()));
				data.add(NutMap.NEW().addv("descript", "是否分班别").addv("name", outputItem.getShift()==1?"分班别":"不分班别"));
				data.add(NutMap.NEW().addv("descript", "站别排序").addv("name", outputItem.getSort_station()));
				data.add(NutMap.NEW().addv("descript", "项目排序").addv("name", outputItem.getSort_item()));
				nmItem.addv("data", data);
				listNmItem.add(nmItem);
			}
			nmStation.addv("data", listNmItem);
			listNmStation.add(nmStation);
		}
		nmMachine.addv("data", listNmStation);
		return nmMachine;
	}
	/**
	 * 从产出数据表中获取所有的不重复机种ID
	 * @return
	 */
	public List<Integer> findMachineIds(){
		Sql sql = Sqls.create("SELECT machineId FROM tb_output_item GROUP BY machineId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("machineId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
	
	/**
	 * 从产出数据表中获取所有的不重复机种对象
	 * @return
	 */
	public List<DataMachine> findMachines(){
		List<DataMachine> machines = new ArrayList<>();
		List<Integer> ids = findMachineIds();
		for(int id : ids){
			machines.add(dao.fetch(DataMachine.class, id));
		}
		return machines;
	}
	/**
	 * 从产出数据表中更具用户获取所有的不重复机种ID
	 * @return
	 */
	public List<Integer> findMachineIds(User user){
		Sql sql = Sqls.create("SELECT machineId FROM tb_output_item where opUserId = "+user.getId()+" GROUP BY machineId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("machineId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
	
	//================================================
	/**
	 * 从产出数据表中获取所有的不重复站别ID
	 * @return
	 */
	public List<Integer> findStationIds(int machineId){
		Sql sql = Sqls.create("SELECT stationId FROM tb_output_item where machineId="+machineId+" GROUP BY stationId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("stationId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
	
	/**
	 * 从产出数据表中获取所有的不重复站别对象
	 * @return
	 */
	public List<DataStation> findStation(int machineId){
		List<DataStation> stations = new ArrayList<>();
		List<Integer> ids = findStationIds(machineId);
		for(int id : ids){
			stations.add(dao.fetch(DataStation.class, id));
		}
		return stations;
	}
	/**
	 * 从产出数据表中更具用户获取所有的不重复站别ID
	 * @return
	 */
	public List<Integer> findStationIds(int machineId, User user){
		Sql sql = Sqls.create("SELECT stationId FROM tb_output_item where machineId="+machineId+" and opUserId = "+user.getId()+" GROUP BY stationId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("stationId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
	
	//================================================
	/**
	 * 从产出数据表中获取所有的不重复项目ID
	 * @return
	 */
	public List<Integer> findItemIds(int machineId,int stationId){
		Sql sql = Sqls.create("SELECT itemId FROM tb_output_item where machineId="+machineId+" and stationId="+stationId+" GROUP BY itemId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("itemId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
	
	/**
	 * 从产出数据表中更具用户获取所有的不重复项目对象
	 * @return
	 */
	public List<DataItem> findItem(int machineId, int stationId){
		List<DataItem> items = new ArrayList<>();
		List<Integer> ids = findItemIds(machineId, stationId);
		for(int id : ids){
			items.add(dao.fetch(DataItem.class, id));
		}
		return items;
	}
	/**
	 * 从产出数据表中更具用户获取所有的不重复项目ID
	 * @return
	 */
	public List<Integer> findItemIds(int machineId, int stationId, User user){
		Sql sql = Sqls.create("SELECT itemId FROM tb_output_item where machineId="+machineId+" and stationId="+stationId+" and opUserId = "+user.getId()+" GROUP BY itemId");
		sql.setCallback(new SqlCallback() {
			@Override
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				// TODO Auto-generated method stub
				List<Integer> list = new ArrayList<>();
				while(rs.next()){
					list.add(rs.getInt("itemId"));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(Integer.class);
	}
}
